package fr.cpe.dp.projet2.rmi.client;

import fr.cpe.dp.projet2.rmi.IRmiMusicService;
import fr.cpe.dp.projet2.rmi.IRmiServerMusicService;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.rmi.Naming;
import java.rmi.RemoteException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFrame;

public class RmiClientMusicService {
    private IRmiServerMusicService serveur;
    private RmiClientMusicServiceView rmiClientMusicServiceView;
    private Object[] musicServices;
    private String serviceName;
    private String serverIp;
            
    public RmiClientMusicService(RmiClientMusicServiceView rmiClientMusicServiceView, String serviceName, String serverIp) {
        this.rmiClientMusicServiceView = rmiClientMusicServiceView;
        this.serviceName = serviceName;
        this.serverIp = serverIp;
        this.musicServices = getListeServices();
        
        for(Object musicService : this.musicServices) {
            this.rmiClientMusicServiceView.addServiceToComboBox(musicService.toString());
        }
        
        bindListenners();
    }
    
    public void bindListenners() {
        rmiClientMusicServiceView.addListServicesListenner(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                try {
                    Object selection = rmiClientMusicServiceView.getSelectedService();
                    IRmiMusicService service = serveur.getService(selection);
                    JFrame serviceIHM = service.getIHM();
                    rmiClientMusicServiceView.startIHM(serviceIHM);
                } catch (RemoteException ex) {
                    Logger.getLogger(RmiClientMusicService.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        });
    }
     
    protected Object[] getListeServices() {
        Object obj = null;
        Object[] services = null;

        try {
            obj = Naming.lookup("rmi://" + serverIp + "/" + serviceName);
            //obj = Naming.lookup(serviceName);
        } catch (Exception ex) {
            ex.printStackTrace();
        }

        serveur = (IRmiServerMusicService) obj;
        
        try {
            services = serveur.getListeServices();
            return services;
        } catch (RemoteException ex) {
            Logger.getLogger(RmiClientMusicService.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        return null;
    }
}
